package com.mcptt.http.operator.online;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import com.cloudptt.api.product.log.Log;
import com.mcptt.comm.CommonFunc;
import com.mcptt.db.model.MapPointInfo;
import com.mcptt.db.op.MapDbOperator;
import com.mcptt.http.operator.IHttpAddrOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OnlineLoader implements Callback{
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url = ":8080/txtapi/list_online_users";;
	private static final int ConnectionTimeout = 30 * 1000;
	private static final int SoTimeout = 30 * 1000;
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private String svrIp = null;
	private MapDbOperator dbOperator = null;
	protected IHttpAddrOpCb callback = null;

	public OnlineLoader(String svrIp,MapDbOperator dbOperator,IHttpAddrOpCb callback)
	{
		this.svrIp = svrIp;
		this.dbOperator = dbOperator;
		this.callback = callback;
	}

	public void load() {
		final String url = HTTP_KEY + svrIp + Sub_Url;


		new Thread(new Runnable(){
			@Override
			public void run() 
			{
				try {
					doHttpGet(url);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doHttpGet(String url) throws Exception
	{
		Log.debug(getClass(), "doHttpGet url = " + url);
		OkHttpUtils.getInstance().doGet(url, this);
		if(dbOperator != null)
		{
			this.dbOperator.cleanAllLogin();
		}
		
	}

	private void saveToDb(List<MapPointInfo> pointList)
	{
		if(dbOperator == null)
		{
			return;
		}
		this.dbOperator.cleanAllLogin();
		Log.debug(getClass(), "saveAddressToDb pointList = " + pointList);
		for(Iterator<MapPointInfo> itor = pointList.iterator();itor.hasNext();)
		{
			MapPointInfo point = itor.next();
			dbOperator.insertOrUptNewPoint(point);
		}
	}

	private void sendOpResultMsg(boolean isSuc)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
			case OP_SUC:
				if(callback != null)
				{
					callback.onOnlineUptResult(true);
				}
				break;
			case OP_FAILED:
				if(callback != null)
				{
					callback.onOnlineUptResult(false);
				}
				break;
			}
		}
	};

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		// TODO Auto-generated method stub
		sendOpResultMsg(false);
	}

	@Override
	public void onResponse(Call arg0, Response response) throws IOException {
		// TODO Auto-generated method stub
		if(response == null)
		{
			sendOpResultMsg(false);
			return;
		}

		Log.debug(getClass(), "onResponse isSuccessful = " + response.isSuccessful());
		if(response.isSuccessful())
		{

			InputStream  instreams = response.body().byteStream(); 
			String content = CommonFunc.convertStreamToString(instreams);//.convertStreamToString(instreams,"user_not_registered");

			Log.debug(getClass(), "onResponse Content = " + content);


			OnlineParser parser = new OnlineParser();
			List<MapPointInfo> pointList = parser.parseContentStr(content);

			if(pointList != null
					&& pointList.size() > 0)
			{
				saveToDb(pointList);
				sendOpResultMsg(true);
			}
			else
			{
				sendOpResultMsg(false);
			}
		}
		else
		{
			sendOpResultMsg(false);
			//	    notifyFailed(parserCallback,"readFromSvr code = " + code);
		}
	}
}
